package com.jdk.demo.fileChannel.batchWrite;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test3_2 {
	
	private static FileOutputStream fosRef;
	private static FileChannel fileChannel;

	// 验证write方法是同步的
	public static void main(String[] args) throws Exception {
		fosRef = new FileOutputStream("c.txt");
		fileChannel = fosRef.getChannel();
		
		for (int i = 0; i < 10; i++) {
			Thread thread1 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer buffer1 = ByteBuffer.wrap("ooooo1\r\n".getBytes());
						ByteBuffer buffer2 = ByteBuffer.wrap("ooooo2\r\n".getBytes());
						ByteBuffer[] bufferArray = new ByteBuffer[]{buffer1, buffer2};
						fileChannel.write(bufferArray);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			Thread thread2 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer buffer1 = ByteBuffer.wrap("zzzzz1\r\n".getBytes());
						ByteBuffer buffer2 = ByteBuffer.wrap("zzzzz2\r\n".getBytes());
						ByteBuffer[] bufferArray = new ByteBuffer[]{buffer1, buffer2};
						fileChannel.write(bufferArray);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			thread1.start();
			thread2.start();
		}
		
		// 从输出结果上看，"ooooo1"和"ooooo2"都是以组为单位出现的，"zzzzz1"和"zzzzz2"也是，说明write(ByteBuffer[])具有同步性
		Thread.sleep(3000);
		fileChannel.close();
		fosRef.close();
	}
	
}
